<?php

class Products extends fvUploaded implements iLogger {
    
    protected $currentEntity = '';
    
    function __construct () {
        $this->currentEntity = __CLASS__;
        parent::__construct(fvSite::$fvConfig->get("entities.{$this->currentEntity}.fields"), 
                            fvSite::$fvConfig->get("entities.{$this->currentEntity}.table_name"), 
                            fvSite::$fvConfig->get("entities.{$this->currentEntity}.primary_key", "id"));
    }
    
    public function getLogMessage($operation) {
        $message = "Продукт был ";
        switch ($operation) {
            case Log::OPERATION_INSERT: $message .= "создан ";break;
            case Log::OPERATION_UPDATE: $message .= "изменен ";break;
            case Log::OPERATION_DELETE: $message .= "удален ";break;
            case Log::OPERATION_ERROR: $message = "Произошла ошибка при операции с записью ";break;
        }
        $user = fvSite::$fvSession->getUser();
        $message .= "в ".date("Y-m-d H:i:s").". Менеджер [".$user->getPk()."] " . $user->getLogin() . " (" . $user->getFullName() . ")";
        return $message;    
    }
    
    public function getLogName() {
        return $this->title;    
    }
    
    public function putToLog($operation) {
        $logMessage = new Log();
        $logMessage->operation = $operation;
        $logMessage->object_type = __CLASS__;
        $logMessage->object_name = $this->getLogName();
        $logMessage->object_id = $this->getPk();
        $logMessage->manager_id = (fvSite::$fvSession->getUser())?fvSite::$fvSession->getUser()->getPk():-1;
        $logMessage->message = $this->getLogMessage($operation);
        $logMessage->edit_link = fvSite::$fvConfig->get('dir_web_root')."products/edit/?id=".$this->getPk();
        $logMessage->save();
    }

	public function validateTitle($value) {
        if (strlen($value) == 0)
			$valid = false;
		else
			$valid = true;
        $this->setValidationResult('title', $valid, 'Поле "Название" не может быть пустым');
        return $valid;
    }
    
	public function validatePrice($value) {
        if (!is_numeric($value)){
			$valid = false;
			$message = 'Поле "Цена" должно быть числом';
        }
        elseif ($value <= 0) {
        	$valid = false;
			$message = 'Поле "Цена" должно быть больше нуля';
        }
		else{
			$valid = true;
		}
        $this->setValidationResult('price', $valid, $message);
        return $valid;
    }
    
    public function validateCategory_id($value){
    	$loggedUser = fvSite::$fvSession->getUser();
    	if ($loggedUser->is_root || $loggedUser->group_id == 1){
    		return true;
    	}
    	else{
    		$sections = array();
    		foreach ($loggedUser->categories_permitions as $cp){
    			$sections = array_unique(array_merge(SectionsManager::getInstance()->getSectionIDs($cp), $sections));
    		}
	    	$valid = in_array($value, $sections);
	    	$this->setValidationResult('category_id', $valid, "Вы не можете сохранять товары в указанную Вами категорию");
	    	return $valid;
    	}
    }
    
	public function validateDiscount($value) {
        if (!is_numeric($value)){
			$valid = false;
			$message = 'Поле "Скидка" должно быть числом';
        }
        elseif ($value < 0) {
        	$valid = false;
			$message = 'Поле "Скидка" должно быть больше нуля';
        }
		elseif ($value > 100) {
        	$valid = false;
			$message = 'Поле "Скидка" не может быть больше 100';
        }
		else{
			$valid = true;
		}
        $this->setValidationResult('discount', $valid, $message);
        return $valid;
    }
    
	public function saveUploadFile($fieldName, $origFile, $fileName) {
        parent::saveUploadFile($fieldName, $origFile, $fileName);
        fvMediaLib::createThumbnail($this->getImageDir().$fileName, $this->getImageDir().$this->getImageName($fileName,self::IMAGE_TYPE_LARGE), array('type' => self::IMAGE_TYPE_LARGE, 'resize_type' => fvMediaLib::THUMB_SQUADRE));
        fvMediaLib::createThumbnail($this->getImageDir().$fileName, $this->getImageDir().$this->getImageName($fileName,self::IMAGE_TYPE_SMALL), array('type' => self::IMAGE_TYPE_SMALL, 'resize_type' => fvMediaLib::THUMB_SQUADRE));
        fvMediaLib::createThumbnail($this->getImageDir().$fileName, $this->getImageDir().$this->getImageName($fileName,self::IMAGE_TYPE_THUMB), array('type' => self::IMAGE_TYPE_THUMB, 'resize_type' => fvMediaLib::THUMB_SQUADRE));
    }
}

?>
